#!/bin/bash

# macOS CPU Core Frequency Monitor
# This script monitors the frequency of each CPU core in real-time on macOS systems.

# Check if running on macOS
if [[ "$OSTYPE" != "darwin"* ]]; then
    echo "This script is intended for macOS only."
    exit 1
fi

# Function to get CPU frequency information
get_cpu_frequency() {
    # Use powermetrics to get CPU information (requires sudo)
    sudo powermetrics --samplers cpu_power -i 1000 -n 1 2>/dev/null
}

# Function to parse and display CPU core frequencies
display_frequencies() {
    # Get raw frequency data
    local freq_data=$(get_cpu_frequency)
    
    # Counter for CPU cores
    local core_count=0
    
    # Convert freq_data to an array of lines
    IFS=$'\n' read -d '' -ra lines <<< "$freq_data"
    
    # Parse and display each core's frequency
    for line in "${lines[@]}"; do
        if [[ $line =~ CPU\ Average\ frequency\ as\ fraction\ of\ nominal.*\((.*)\ Mhz\) ]]; then
            freq=${BASH_REMATCH[1]}
            # Convert frequency from MHz to GHz for readability
            freq_ghz=$(echo "scale=2; $freq/1000" | bc)
            printf "Core %2d: %6.2f GHz\n" "$core_count" "$freq_ghz"
            ((core_count++))
        fi
    done
    
    # If no cores were found, show a message
    if [ $core_count -eq 0 ]; then
        echo "No CPU frequency data found."
    fi
    
    # Add empty lines to clear any remaining content from previous display
    echo ""
    echo ""
}

# Main monitoring loop
echo "Starting CPU Core Frequency Monitor..."
echo "Press Ctrl+C to stop."

# Display header once
echo "CPU Core Frequency Monitor (Press Ctrl+C to stop)"
echo "----------------------------------------"

while true; do
    # Save cursor position
    tput sc
    
    # Display frequencies
    display_frequencies
    
    # Restore cursor position
    tput rc
    
    sleep 2
done